package com.shqcjd.generalplatformprojectclient.ui.activity;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Process;
import android.support.annotation.NonNull;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.orhanobut.logger.Logger;
import com.pgyersdk.javabean.AppBean;
import com.pgyersdk.update.PgyUpdateManager;
import com.pgyersdk.update.UpdateManagerListener;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreator;
import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreator;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.shqcjd.generalplatformprojectclient.R;
import com.shqcjd.generalplatformprojectclient.api.ApiService;
import com.shqcjd.generalplatformprojectclient.app.AppConstant;
import com.shqcjd.generalplatformprojectclient.app.MyApp;
import com.shqcjd.generalplatformprojectclient.helper.rxjavahelper.RxObserver;
import com.shqcjd.generalplatformprojectclient.helper.rxjavahelper.RxSchedulersHelper;
import com.shqcjd.generalplatformprojectclient.model.ResponseData;
import com.shqcjd.generalplatformprojectclient.model.pojo.GuideListBean;
import com.shqcjd.generalplatformprojectclient.model.pojo.RemoteGuidanceBean;
import com.shqcjd.generalplatformprojectclient.model.pojo.eventbus.FinishActivityEvent;
import com.shqcjd.generalplatformprojectclient.model.pojo.eventbus.GuidanceFinishBean;
import com.shqcjd.generalplatformprojectclient.ui.adapter.StickyAdapter;
import com.shqcjd.generalplatformprojectclient.ui.base.BaseActivity;
import com.shqcjd.generalplatformprojectclient.ui.base.BasePresenter;
import com.shqcjd.generalplatformprojectclient.util.AppManager;
import com.shqcjd.generalplatformprojectclient.util.PrefUtils;
import com.shqcjd.generalplatformprojectclient.util.ToastUtils;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuRecyclerView;
import com.yanzhenjie.recyclerview.swipe.widget.StickyNestedScrollView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import es.dmoral.toasty.Toasty;
import io.agora.AgoraAPI;
import io.agora.AgoraAPIOnlySignal;
import io.agora.IAgoraAPI;
import io.agora.rtc.RtcEngine;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

import static com.pgyersdk.update.UpdateManagerListener.startDownloadTask;

public class MainActivity extends BaseActivity {


    @BindView(R.id.rl_user)
    RelativeLayout rlUser;
    @BindView(R.id.rl_main)
    RelativeLayout rlMain;
    @BindView(R.id.tv_user_phone)
    TextView tvUserPhone;
    @BindView(R.id.ll_change_pwd)
    LinearLayout llChangePwd;
    @BindView(R.id.tv_cache_size)
    TextView tvCacheSize;
    @BindView(R.id.ll_clear_cache)
    LinearLayout llClearCache;
    @BindView(R.id.tv_phone_number)
    TextView tvPhoneNumber;
    @BindView(R.id.ll_service_number)
    LinearLayout llServiceNumber;
    @BindView(R.id.btn_quit)
    Button btnQuit;
    @BindView(R.id.drawer_layout)
    DrawerLayout drawer_layout;
    @BindView(R.id.rv_main)
    SwipeMenuRecyclerView rvMain;
    @BindView(R.id.scroll_view)
    StickyNestedScrollView scrollView;
    @BindView(R.id.tv_content)
    TextView tv_content;
    @BindView(R.id.swipe_refresh)
    SmartRefreshLayout swipeRefresh;
    @BindView(R.id.ll_main_isGuide)
    LinearLayout llMainIsGuide;
    @BindView(R.id.switch_use_glass)
    Switch switch_use_glass;
    private AgoraAPIOnlySignal agoraAPIOnlySignal;
    private Context context;
    private StickyAdapter adapter;
    private RemoteGuidanceBean remoteGuidanceBean;
    private String remoteAccount;
    private boolean isKillProcess = true;
    private List<GuideListBean.ContentBean> mList = new ArrayList<>();

    private int page = 1;
    private int pageTotal = 1;
    private boolean glass_state;

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_main;
    }

    @Override
    public void init() {
        super.init();
        context = this;
//        glass_state = PrefUtils.getBoolean(this, PrefUtils.USE_GLASS, false);
        checkDownload();
    }

    /**
     * 下载更新
     */
    private void checkDownload(){
        PgyUpdateManager.register(MainActivity.this,
                new UpdateManagerListener() {
                    @Override
                    public void onUpdateAvailable(final String result) {

                        // 将新版本信息封装到AppBean中
                        final AppBean appBean = getAppBeanFromString(result);
                        new AlertDialog.Builder(MainActivity.this)
                                .setTitle("更新")
                                .setMessage(appBean.getReleaseNote())
                                .setNegativeButton(
                                        "确定",
                                        new DialogInterface.OnClickListener() {

                                            @Override
                                            public void onClick(
                                                    DialogInterface dialog,
                                                    int which) {
                                                checkDownloadPermissions(appBean);
                                            }
                                        }).show();
                    }

                    @Override
                    public void onNoUpdateAvailable() {
                    }
                });
    }

    /**
     * 下载更新权限
     */
    private void checkDownloadPermissions(AppBean appBean) {
        RxPermissions permissions = new RxPermissions(this);
        permissions.setLogging(true);
        permissions.request(
                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        if (aBoolean) {
                            startDownloadTask(
                                    MainActivity.this,
                                    appBean.getDownloadURL());
                        } else {
                            Toasty.warning(MainActivity.this, "更新需要sd卡读写权限").show();
                        }
                    }
                });
    }

    @Override
    public void initView() {
        EventBus.getDefault().register(this);//订阅
        agoraAPIOnlySignal = MyApp.the().getmAgoraAPI();
        switch_use_glass.setChecked(glass_state);
//        if (!glass_state) {//未使用眼镜
//            //初始化声网
//            initAgora();
//        }

        tvUserPhone.setText(PrefUtils.getString(context, PrefUtils.USER_PHONE, ""));
        rvMain.setNestedScrollingEnabled(false);
        adapter = new StickyAdapter(context, mList);
        rvMain.setLayoutManager(new LinearLayoutManager(context));

        rvMain.setAdapter(adapter);
        adapter.setOnGuideIngClickListener(new StickyAdapter.setOnGuideIngClickListener() {
            @Override
            public void onReceive() {
                if (remoteGuidanceBean != null && remoteAccount != null) {
                    inviteAccept();
                    closeGuideIng();
                }
            }

            @Override
            public void onRefuse() {
                if (remoteGuidanceBean != null && remoteAccount != null) {
                    agoraAPIOnlySignal.channelInviteRefuse(remoteGuidanceBean.roomId, remoteAccount, 0, null);
                    closeGuideIng();

                }
            }
        });

        swipeRefresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                getGuideList(0);
            }
        });

        swipeRefresh.setDefaultRefreshHeaderCreator(new DefaultRefreshHeaderCreator() {
            @Override
            public RefreshHeader createRefreshHeader(Context context, RefreshLayout layout) {
                layout.setPrimaryColorsId(R.color.black, android.R.color.black);
                MaterialHeader materialHeader = new MaterialHeader(context);
                materialHeader.setColorSchemeColors(Color.BLACK);
                return materialHeader;
            }
        });

        swipeRefresh.setDefaultRefreshFooterCreator(new DefaultRefreshFooterCreator() {
            @Override
            public RefreshFooter createRefreshFooter(Context context, RefreshLayout layout) {
                return new ClassicsFooter(context).setDrawableSize(20);
            }
        });

        swipeRefresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                if (page < pageTotal) {
                    getGuideList(1);
                } else {
                    ToastUtils.showShort(context, "沒有更多内容");
                    swipeRefresh.finishLoadMoreWithNoMoreData();
                }
            }
        });

        drawer_layout.addDrawerListener(new DrawerLayout.DrawerListener() {


            @Override
            public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {

            }

            @Override
            public void onDrawerOpened(@NonNull View drawerView) {
                getUseGlassState();
            }

            @Override
            public void onDrawerClosed(@NonNull View drawerView) {

            }

            @Override
            public void onDrawerStateChanged(int newState) {

            }
        });

        getUseGlassState();
        getGuideList(0);
    }


    /**
     * 接受邀请
     */
    private void inviteAccept() {
        Map<String, String> map = new HashMap<>();
        map.put("operation", "1");//0 拒绝 1 接受 2结束
        map.put("roomId", remoteGuidanceBean.roomId);
        String json = new Gson().toJson(map);
        ApiService.inviteHandle(json)
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData>() {
                    @Override
                    public void _onNext(ResponseData responseData) {
                        agoraAPIOnlySignal.channelInviteAccept(remoteGuidanceBean.roomId, remoteAccount, 0, null);
                        Intent intent = new Intent(MainActivity.this, RemoteGuidanceActivity.class);
                        intent.putExtra("remoteGuidanceBean", remoteGuidanceBean);
                        startActivity(intent);
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        Toasty.info(MainActivity.this, "接受远程指导失败").show();
                    }
                });
    }


    private void initAgora() {
        Logger.i("初始化了");
        int userId = PrefUtils.getInt(this, PrefUtils.USER_USER_ID, -1);
        //登出
        agoraAPIOnlySignal.logout();
        //登录声网信令系统
        agoraAPIOnlySignal.login2(getString(R.string.agora_app_id), userId + "", "_no_need_token", 0, "", 5, 3);


    }

    @Override
    protected void onResume() {
        super.onResume();
        getGuideList(0);
        addCallback();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        if (!switch_use_glass.isChecked()) {//不使用眼镜则重启信令
            initAgora();
        }

    }

    private void addCallback() {
        agoraAPIOnlySignal.callbackSet(new AgoraAPI.CallBack() {

            @Override
            public void onLoginSuccess(int i, int i1) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Logger.i("Agora 信令登入");
                    }
                });
            }

            @Override
            public void onLogout(int i) {
                Logger.i("Agora 信令登出");
            }

            @Override
            public void onLoginFailed(final int i) {
                Logger.e("Agora 信令onLoginFailed");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (i == IAgoraAPI.ECODE_LOGIN_E_NET) {
                        }
                    }
                });
            }

            @Override
            public void onError(String s, int i, String s1) {
                Logger.e("Agora 信令onError s:" + s + " i:" + i + " s1:" + s1);
                if (i == 208) {//用户已登录，再次发起登录会触发该错误 可以忽视该错误

                }
            }

            //呼叫取消时的回调
            @Override
            public void onInviteEndByPeer(String channelID, String account, int uid, String extra) {
                super.onInviteEndByPeer(channelID, account, uid, extra);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        closeGuideIng();
                        Logger.i("Agora 呼叫取消:");
                    }
                });
            }

            //收到对方呼叫时调用
            @Override
            public void onInviteReceived(String channelID, String account, int uid, String extra) {
                super.onInviteReceived(channelID, account, uid, extra);
                Logger.i("Agora 收到对方呼叫:");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        remoteAccount = account;
                        remoteGuidanceBean = new Gson().fromJson(extra, RemoteGuidanceBean.class);
                        adapter.setGuideIng(remoteGuidanceBean);
                        adapter.isGuideIng = true;
                        adapter.notifyDataSetChanged();
                        scrollView.scrollTo(0, 0);
                        llMainIsGuide.setVisibility(View.INVISIBLE);
                        Logger.i("接收呼叫:" + remoteGuidanceBean);
                    }
                });
            }
        });
    }

    /**
     * 关闭远程指导的ui
     *
     * @param
     */
    private void closeGuideIng() {
        adapter.isGuideIng = false;
        adapter.notifyDataSetChanged();
        isShowTips();
    }

    /**
     * 是否显示暂无远程指导的提示
     */
    private void isShowTips() {
        if (adapter.getmList() == null) {
            return;
        }
        if (adapter.getmList().size() == 0) {
            llMainIsGuide.setVisibility(View.VISIBLE);
        } else {
            llMainIsGuide.setVisibility(View.INVISIBLE);
        }
    }

    @OnClick({R.id.rl_user, R.id.ll_change_pwd, R.id.ll_clear_cache, R.id.ll_service_number, R.id.btn_quit, R.id.switch_use_glass})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_user://个人中心
                drawer_layout.openDrawer(Gravity.LEFT);
                break;
            case R.id.ll_change_pwd://更改密码
                startActivity(new Intent(this, ChangePasswordActivity.class));
                break;
            case R.id.ll_clear_cache://清除缓存
                Toasty.info(this, "清除缓存").show();
                break;
            case R.id.ll_service_number://客服电话
                RxPermissions rxPermission = new RxPermissions(MainActivity.this);
                rxPermission.requestEach(
                        Manifest.permission.CALL_PHONE)
                        .subscribe(new Consumer<Permission>() {
                            @Override
                            public void accept(Permission permission) throws Exception {
                                if (permission.granted) {
                                    // 用户已经同意该权限
                                    callPhone(tvPhoneNumber.getText().toString());
                                } else if (permission.shouldShowRequestPermissionRationale) {
                                    // 用户拒绝了该权限，没有选中『不再询问』（Never ask again）,那么下次再次启动时，还会提示请求权限的对话框
                                    ToastUtils.showShort(MainActivity.this, "需要申请权限才能使用该功能");
                                } else {
                                    // 用户拒绝了该权限，并且选中『不再询问』
                                    ToastUtils.showShort(MainActivity.this, "请在手机的设置中打开拨打电话权限");
                                }
                            }
                        });
                break;
            case R.id.btn_quit://退出程序
                signOut();
                break;
            case R.id.switch_use_glass://使用眼镜

                useGlass(switch_use_glass.isChecked());

                break;

        }
    }

    /**
     * 使用眼镜
     *
     * @param checked
     */
    private void useGlass(boolean checked) {
//        PrefUtils.setBoolean(this, PrefUtils.USE_GLASS, checked);
        if (checked) {//使用眼镜则 手机退出信令
            useGlass(1);
        } else {
            useGlass(0);
        }
    }


    /**
     *
     * @param isUse 使用眼镜0：不使用 1：使用
     */
    private void useGlass(int isUse){
        ApiService.useGlass(isUse)
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                        switch_use_glass.setClickable(false);
                        showWaitingDialog("设置中...");
                    }

                    @Override
                    public void _onNext(ResponseData responseData) {
                        switch_use_glass.setClickable(true);
                        hideWaitingDialog();
                        if (isUse == 1) {//设置使用眼镜
                            if (responseData.code == 0) {
                                if (agoraAPIOnlySignal != null)
                                    agoraAPIOnlySignal.logout();
                            } else {//设置失败
                                //获取眼镜的使用状态
                                switch_use_glass.setChecked(false);
                            }
                        } else if (isUse == 0) {//设置不使用眼镜
                            if (responseData.code == 0) {
                                initAgora();
                            } else {//设置失败
                                //获取眼镜的使用状态
                                switch_use_glass.setChecked(true);
                            }
                        }

                    }

                    @Override
                    public void _onError(String errorMessage) {
                        switch_use_glass.setClickable(true);
                        hideWaitingDialog();
                        Toasty.normal(MainActivity.this,errorMessage).show();
                        if (isUse == 1) {//设置使用眼镜
                            switch_use_glass.setChecked(false);
                        } else if (isUse == 0) {
                            switch_use_glass.setChecked(true);
                        }
                    }
                });
    }

    /**
     * 获取眼镜的使用状态
     */
    private void getUseGlassState(){
        ApiService.useGlassState()
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<Integer>>() {
                    @Override
                    public void _onNext(ResponseData<Integer> responseData) {
                        if (responseData.code == 0) {
                            if (responseData.data == 1) {//使用眼镜中
                                switch_use_glass.setChecked(true);
                            } else if (responseData.data == 0) {//未使用眼镜
                                switch_use_glass.setChecked(false);
                                initAgora();
                            }
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                    }
                });
    }


    public void callPhone(String phoneNum) {
        Intent intent = new Intent(Intent.ACTION_DIAL);
        Uri data = Uri.parse("tel:" + phoneNum);
        intent.setData(data);
        startActivity(intent);
    }


    public long preTime;
    public final long TWO_SECOND = 2 * 1000;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            long currentTime = System.currentTimeMillis();
            if (drawer_layout.isDrawerOpen(Gravity.LEFT)) {
                drawer_layout.closeDrawers();
            } else
                //  moveTaskToBack(false);
                if (currentTime - preTime > TWO_SECOND) {
                    Toasty.warning(MainActivity.this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                    // 更新时间
                    preTime = System.currentTimeMillis();

                } else {
                    MainActivity.this.finish();
                }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onFinishActivityEvent(FinishActivityEvent event) {
        Toasty.normal(this,"用户登录失效").show();
        signOut();
    }

    /**
     * 远程指导结束刷新页面
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void guidanceFinish(GuidanceFinishBean event) {
        getGuideList(0);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);//解除订阅
        if (isKillProcess) {        //销毁RtcEngine
            RtcEngine.destroy();
            agoraAPIOnlySignal.logout();
            Process.killProcess(Process.myPid());
        }

    }

    @Override
    protected void onStop() {
        super.onStop();
        closeMenu();
    }


    private void closeMenu() {
        if (drawer_layout != null) {
            if (drawer_layout.isDrawerOpen(Gravity.LEFT)) {
                drawer_layout.closeDrawers();
            }
        }
    }

    /**
     * 0代表刷新   1代表加载更多
     *
     * @param loadMoreOrRefresh
     */
    public void getGuideList(int loadMoreOrRefresh) {
        int p = (loadMoreOrRefresh == 0 ? 1 : page + 1);
        ApiService.guideList(p)
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<GuideListBean>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                    }

                    @Override
                    public void _onNext(ResponseData<GuideListBean> data) {
                        if (data.code == 0) {
                            if (loadMoreOrRefresh == 0) {
                                mList.clear();
                                page = 1;
                            } else {
                                page = 1 + page;
                            }
                            pageTotal = data.data.totalPages;
                            mList.addAll(data.data.content);
                            adapter.notifyDataSetChanged();
                            isShowTips();
                        } else {
                            ToastUtils.showShort(context, data.message);
                        }
                        if (loadMoreOrRefresh == 0) {
                            swipeRefresh.finishRefresh();
                        } else {
                            swipeRefresh.finishLoadMore();
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        if (loadMoreOrRefresh == 0) {
                            swipeRefresh.finishRefresh();
                        } else {
                            swipeRefresh.finishLoadMore();
                        }
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        if (loadMoreOrRefresh == 0) {
                            swipeRefresh.finishRefresh();
                        } else {
                            swipeRefresh.finishLoadMore();
                        }
                    }
                });
    }

    /**
     * 退出登录
     */
    private void signOut() {
        isKillProcess = false;
        PrefUtils.setString(this, PrefUtils.COMPANY_NAME, "");
        PrefUtils.setInt(this, PrefUtils.COMPANY_ID, 0);
        PrefUtils.setString(this, PrefUtils.USER_PHONE, "");
        PrefUtils.setInt(this, PrefUtils.USER_ROLE_ID, 0);
        PrefUtils.setInt(this, PrefUtils.USER_USER_ID, 0);
        PrefUtils.setString(this, AppConstant.TOKEN_KEY, "");
        AppManager.getAppManager().finishAllActivity();
        Intent it = new Intent(this, LoginActivity.class);
        startActivity(it);
    }

}
